//
//  TouTiaoTableVC.m
//  News
//
//  Created by lanou3g on 15/11/4.
//  Copyright © 2015年 songhaowen. All rights reserved.
//

#import "TouTiaoTableVC.h"
#import "LoadData.h"
#import "JQnewsModel.h"
#import "CellOneImg.h"
#import "CellTwoImg.h"
#import "MJRefresh.h"
#import "DedailVC.h"
#import "AFNetworkReachabilityManager.h"
@interface TouTiaoTableVC ()
@property(nonatomic,strong)NSString *category;
@property(nonatomic,assign)int num;//这里是想外界想一次刷新多少条就传几,但是我固定写了20条  没用上这个
@property(nonatomic,strong)NSMutableArray *newsArray;//新闻数组里面放的JQnewsModel新闻模型,一个模型代表一个新闻
@end

@implementation TouTiaoTableVC

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if ([self.title isEqualToString:@"娱乐"])
    {
        [self setUpWithCategory:@"T1348648517839" withNum:20];
        [self downUpFresh];
    }
    
    else if([self.title isEqualToString:@"最热"])
    {
        [self setUpWithCategory:@"T1348647853363" withNum:20];
        [self downUpFresh];
    }
    
    else if([self.title isEqualToString:@"实时体育"])
    {
        [self setUpWithCategory:@"T1348649079062" withNum:20];
        [self downUpFresh];
    }
    
    else if([self.title isEqualToString:@"科技快报"])
    {
        [self setUpWithCategory:@"T1348649580692" withNum:20];
        [self downUpFresh];
    }
    
    else if([self.title isEqualToString:@"财经频道"])
    {
        [self setUpWithCategory:@"T1348648756099" withNum:20];
        [self downUpFresh];
    }
    
    else if([self.title isEqualToString:@"社会"])
    {
        [self setUpWithCategory:@"T1348648037603" withNum:20];
        [self downUpFresh];
    }
    
    else if([self.title isEqualToString:@"教育"])
    {
        [self setUpWithCategory:@"T1348654225495" withNum:20];
        [self downUpFresh];
    }
    
    else if([self.title isEqualToString:@"时尚"])
    {
        [self setUpWithCategory:@"T1348650593803" withNum:20];
        [self downUpFresh];
    }
    
    else if([self.title isEqualToString:@"家居"])
    {
        [self setUpWithCategory:@"T1348654105308" withNum:20];
        [self downUpFresh];
    }
    
    else if([self.title isEqualToString:@"游戏"])
    {
        [self setUpWithCategory:@"T1348654151579" withNum:20];
        [self downUpFresh];
    }

    
    dispatch_async(dispatch_get_main_queue(), ^{
        [[LoadData shareInstance] downLoadDataFinished:^{
            int i = 0;
            for (JQnewsModel *model in [LoadData shareInstance].contentArray) {
                [self.newsArray insertObject:model atIndex:i];
            }
            //[self.newsArray addObjectsFromArray:[LoadData shareInstance].contentArray];
            [self.tableView.header endRefreshing];
            //NSLog(@"%@",self.newsArray);
            [self.tableView reloadData];
        } WithUrl:[NSString stringWithFormat:@"http://c.m.163.com/nc/article/headline/%@/%d-%d.html",self.category,0,
                   10]withCategory:self.category];
    });
    
   


}

- (void)viewDidLoad {
    [super viewDidLoad];
  
     [self downUpFresh];//下拉刷新数据
   // [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(DownRefresh)  name:@"ShuaXinA" object:nil];
    
    
    //[self downUpFresh];
}



//下拉刷新数据
- (void)downUpFresh
{
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        int num2 = self.num - 20;
        int num1 = self.num;
        self.num += 20;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [[LoadData shareInstance] downLoadDataFinished:^{
                int i = 0;
                for (JQnewsModel *model in [LoadData shareInstance].contentArray) {
                    [self.newsArray insertObject:model atIndex:i];
                }
                //[self.newsArray addObjectsFromArray:[LoadData shareInstance].contentArray];
                [self.tableView.header endRefreshing];
                //NSLog(@"%@",self.newsArray);
                [self.tableView reloadData];
            } WithUrl:[NSString stringWithFormat:@"http://c.m.163.com/nc/article/headline/%@/%d-%d.html",self.category,num2,
                       num1]withCategory:self.category];
        });
        
        // 结束刷新
        [self.tableView.header endRefreshing];
        
    }];
    

}



-(void)DownRefresh{
    
#pragma mark  blok调网络请求
    void(^WangLuoQingQiu)() = ^(){
        [self downUpFresh];
    
//    int num2 = self.num - 20;
//    int num1 = self.num;
//    self.num += 20;
//    //NSLog(@"%d````%d",num1,num2);
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        [[LoadData shareInstance] downLoadDataFinished:^{
//            int i = 0;
//            for (JQnewsModel *model in [LoadData shareInstance].contentArray) {
//                [self.newsArray insertObject:model atIndex:i];
//            }
//            //[self.newsArray addObjectsFromArray:[LoadData shareInstance].contentArray];
//            [self.tableView.header endRefreshing];
//            //NSLog(@"%@",self.newsArray);
//            [self.tableView reloadData];
//        } WithUrl:[NSString stringWithFormat:@"http://c.m.163.com/nc/article/headline/%@/%d-%d.html",self.category,num2,
//                   num1]withCategory:self.category];
//    });
//        
        
    
};
    
#pragma mark 网络判断
    AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];
    
    [mgr setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
                
            case AFNetworkReachabilityStatusReachableViaWiFi:
            {
                WangLuoQingQiu();
                break;
            }
                
            case AFNetworkReachabilityStatusReachableViaWWAN:
            {
                WangLuoQingQiu();
                break;
            }
                
            case AFNetworkReachabilityStatusNotReachable:
                NSLog(@"没网");
                break;
                
            case AFNetworkReachabilityStatusUnknown:
            {
                NSLog(@"未知的网");
                break;
            }
        }
    }];
    
    [mgr startMonitoring];

    
    
}

//
//#pragma mark 上啦刷新控件
//-(void)UpRefresh{
//      [self setUpData];//上啦数据请求
//      [self.tableView footerEndRefreshing];// 结束刷新(隐藏footer)
//}
//#pragma mark  上拉数据请求并保存到沙盒
//-(void)setUpData
//{
//    //🌹1.从沙盒中请求数据的params
//    JQnewsModel *model = [[JQnewsModel alloc] init];
//    NSMutableDictionary *params =[NSMutableDictionary dictionary];
//    params[@"JQ_id"] = model.photosetID;
//    
//    
//    //🌹2.定义block 加载数据刷UI的时候调用
//    void(^JoinlonResult)(NSArray *) = ^(NSArray *news)
//    {
//        [self.newsArray addObjectsFromArray:news];//把沙盒里的数据有逻辑的放进UI数组(把最新的新闻,添加到数组的最后面)
//        [self.tableView reloadData];//刷新表格
//    };
//    
//    
//    //🌹3.从沙盒中加载新闻数据
//    NSArray *news = [CacheNews newsWithParams:params];//从沙盒里取数据
//    if (news.count)//🐞a.如果沙盒有缓存数据
//    {
//        JoinlonResult(news);//直接调用block给UI加载数据
//    }
//    
//    else//🐞b.如果沙盒没有缓存数据
//    {
//        //发送请求 (开一个子线程里进行 防网差)
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            //发送网络请求
//            [[LoadData shareInstance] downLoadDataFinished:^{
//                
//                [CacheNews saveNews:[LoadData shareInstance].contentArray];//把请求的数据(模型数组)存进沙盒
//                JoinlonResult(news);//调用block给UI加载数据
//                
//            } WithUrl:[NSString stringWithFormat:@"http://c.m.163.com/nc/article/list/%@/20-20.html",self.category] withCategory: self.category];
//            
//        });
//        
//    }
//
//}
//
//
//
//#pragma mark 下拉刷新控件
//-(void)DownRefresh
//{
//      [self setDownData];//下拉数据请求
//      [self.tableView headerEndRefreshing];// 结束刷新(隐藏header)
//}
//#pragma mark 下拉数据请求并保存到沙盒
//-(void)setDownData{
//     //🌹1.从沙盒中请求数据的params
//    JQnewsModel *model = [[JQnewsModel alloc] init];
//    NSMutableDictionary *params =[NSMutableDictionary dictionary];
//    params[@"JQ_id"] = model.;
//    
//    
//     //🌹2.定义block 加载数据刷UI的时候调用
//     void(^JoinlonResult)(NSArray *) = ^(NSArray *news)
//    {
//        
//        
//        //把沙盒里的数据有逻辑的放进UI数组(把最新的新闻,添加到数组的最前面)
//        int i = 0;
//        for (JQnewsModel *model in news) {
//            
//            [self.newsArray insertObject:model atIndex:i];
//            i++;
//        }
//        [self.tableView reloadData];//刷新表格
//    };
//    
//    
//     //🌹3.从沙盒中加载新闻数据
//    NSArray *news = [CacheNews newsWithParams:params];//从沙盒里取数据
//    if (news.count)//🐞a.如果沙盒有缓存数据
//    {
//        JoinlonResult(news);//直接调用block给UI加载数据
//    }
//    
//    else//🐞b.如果沙盒没有缓存数据
//    {
//        //发送请求 (开一个子线程里进行 防网差)
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            //发送网络请求
//            [[LoadData shareInstance] downLoadDataFinished:^{
//                
//                [CacheNews saveNews:[LoadData shareInstance].contentArray];//把请求的数据存进沙盒
//                JoinlonResult(news);//调用block给UI加载数据
//                
//            } WithUrl:[NSString stringWithFormat:@"http://c.m.163.com/nc/article/list/%@/0-20.html",self.category] withCategory: self.category];
//
//        });
//       
//    }
//    
//}



#pragma mark  tableView代理方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

   // return [LoadData shareInstance].contentArray.count;
    return self.newsArray.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    // JQnewsModel *model = [LoadData shareInstance].contentArray[indexPath.row];
     JQnewsModel *model = self.newsArray[indexPath.row];
    if (!model.imgextra) {
        return 120;
    }else{
        return 196;
    }
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
   // JQnewsModel *model = [LoadData shareInstance].contentArray[indexPath.row];
    JQnewsModel *model = self.newsArray[indexPath.row];
    //NSLog(@"%@",[LoadData shareInstance].contentArray);
    if (!model.imgextra ) {
        //1张图cell
        CellOneImg *cell = [CellOneImg cellWithTableView:tableView];//重用
        [cell setUiWith:model];//赋值
        return cell;
    }else{
        //2张图cell
        CellTwoImg *cell = [CellTwoImg cellWithTableView:tableView];//重用
        [cell setUiWith:model];//赋值
        return cell;
    }
}
#pragma mark 点击cell跳到详情界面
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    DedailVC *detailVC = [[DedailVC alloc] init];
    //JQnewsModel *model = [LoadData shareInstance].contentArray[indexPath.row];
     JQnewsModel *model = self.newsArray[indexPath.row];
    detailVC.model = model;
    //detailVC.hidesBottomBarWhenPushed = YES;
    [self presentViewController:detailVC animated:YES completion:nil];
}


#pragma mark 外面传参传入需要类别 个数
-(void)setUpWithCategory:(NSString*)category withNum:(int)num
{
    self.category = category;
    self.num = num;
}
#pragma mark 懒加载
-(NSMutableArray*)newsArray
{
    if (!_newsArray) {
        _newsArray = [NSMutableArray array];
    }
    return _newsArray;
}








/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
